<template>
  <div style="border: 1px solid #ccc; z-index: 100; width: 100%;">
    <!-- 工具栏 -->
    <Toolbar :editor="editorRef as IDomEditor | undefined" :mode="props.mode" style="border-bottom: 1px solid #ccc" />
    <!-- 编辑器 -->
    <Editor 
      v-model="html" 
      :style="props.style" 
      :disabled="props.disabled" 
      :default-config="editorConfig" 
      :mode="props.mode" 
      @onCreated="handleCreated" 
      @onChange="handleChange" 
    />
  </div>
</template>

<script lang="ts" setup>
import "@wangeditor/editor/dist/css/style.css";
import { ref, shallowRef, watch, onBeforeUnmount } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IDomEditor, IEditorConfig } from "@wangeditor/editor";

// 定义 Props 类型
interface EditorFieldProps {
  modelValue: string;
  mode?: string;
  placeholder?: string;
  style?: string;
  disabled?: boolean;
}

// 设置 Props 默认值
const props = withDefaults(defineProps<EditorFieldProps>(), {
  mode: "default",
  placeholder: "",
  style: "height: 300px;",
  disabled: false
});

const emit = defineEmits<{
  (event: 'update:modelValue', value: string): void;
}>();

const editorRef = shallowRef<IDomEditor | null>(null);
const html = ref<string>(props.modelValue);

const editorConfig: Partial<IEditorConfig> = {
  placeholder: props.placeholder,
  readOnly: props.disabled,
  MENU_CONF: {
    uploadImage: {
      server: `${import.meta.env.NODE_ENV === 'development' ? '/api/' : import.meta.env.VITE_APP_DOWNLOAD_IMG_API}common/upload/img`,
      fieldName: "file",
      customInsert(res: any, insertFn: (url: string, alt: string, href: string) => void) {
        insertFn(res.data.src, "", "");
      }
    }
  }
};

watch(() => props.modelValue, (newVal) => {
  if (newVal !== html.value) {
    html.value = newVal;
  }
});

watch(html, (newVal) => {
  emit('update:modelValue', newVal);
});

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor;
};

const handleChange = (editor: IDomEditor) => {
  html.value = editor.getHtml();
};

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor != null) {
    editor.destroy();
  }
});
</script>
<style lang="scss" scoped>

</style>